package com.hujiang.basic.search.common.service;

import com.alibaba.fastjson.JSONObject;
import com.hujiang.basic.framework.core.util.IpUtil;
import com.hujiang.basic.framework.rest.common.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * Created by caolinhua on 2016/12/26.
 */
@Service
@Slf4j
public class WeiXinNotifyServiceImpl implements NotifyService {


    @Value("${notify.weinxin.base.url}")
    private String weixinBaseUrl;

    @Value("${notify.weinxin.token.url}")
    private String tokenUrl;

    @Value("${notify.weixin.users}")
    private String baseUsers;

    private String getTokenFromWeiXin() {
        JSONObject result = JSONObject.parseObject(HttpClientUtil.sendHttpGet(tokenUrl));
        return result != null ? result.getString("access_token") : StringUtils.EMPTY;
    }

    @Override
    public void inform(String users, String content) {
        if (StringUtils.isEmpty(users) || StringUtils.isEmpty(content)) {
            log.info("users : {} , content :{} is not empty", users, content);
        }

        String token = getTokenFromWeiXin();
        if (StringUtils.isEmpty(token)) {
            log.info("wexin's token is empty");
        }

        JSONObject params = new JSONObject();
        JSONObject text = new JSONObject();
        text.put("content", content + "，client ip ：" + IpUtil.getClientIp() + "server ip ： " + IpUtil.getIp());

        params.put("msgtype", "text");
        params.put("agentid", "9");
        params.put("safe", "0");
        params.put("touser", StringUtils.isEmpty(users) ? baseUsers : (users + "|" + baseUsers));
        params.put("text", text);

        String result = HttpClientUtil.sendHttpPost(weixinBaseUrl + token, params.toJSONString());
        log.info("weixin result :{} parameter:{}", result, params.toJSONString());
    }

}
